package com.umeox.watch.prayertime.utils;


import android.os.Parcel;
import android.os.Parcelable;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import com.umeox.moto.common.log.Logger;
import com.umeox.watch.prayertime.base.BaseApp;
import com.umeox.watch.prayertime.bean.PrayerAlarmDetail;
import com.umeox.watch.prayertime.bean.PrayerTimeInfo;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {

    public static final String EXTRA_KEY_ALARM = "alarm_detail";
    public static final String EXTRA_KEY_ID = "id";
    public static final String EXTRA_KEY_AUTO = "auto";
    public static final String EXTRA_KEY_REPEAT_EXPRESSION = "alarm_repeat_expression";

    public static final String ALARM_NOREPEAT_EXP = "0000000";
    public static final String ALARM_EVERYDAY_REPEAT_EXP = "1111111";

    public static final String ACTION_UPDATED_PRAYER_TIME = "com.umeox.watch.intent.action.UPDATE_PRAYER_TIME";

    /**
     * 判断服务器闹钟时间格式是否正确 HH:mm
     */
    public static boolean is24HourFormatTime(String alarmTimeStr) {
        if (TextUtils.isEmpty(alarmTimeStr)) {
            return false;
        }
        String rexp = "^(([0-1][0-9])|2[0-3]):[0-5][0-9]$";
        Pattern pat = Pattern.compile(rexp);
        Matcher mat = pat.matcher(alarmTimeStr);
        return mat.matches();
    }

    /**
     * 判断时间段，重复周期格式是否正确
     * 正确格式：1100011  7个字节长度，只允许0或者1
     */
    public static boolean isInvalidRepeatExpression(String repeatExpression) {
        String rexp = "[0-1]{7}";
        return Pattern.compile(rexp).matcher(repeatExpression).matches();
    }


    //重复周期只有星期天
    private static final String ONE_SUNDAY_EXP = "1000000";


    /**
     * Combine a list of strings in an <code>Object[]</code> into a single
     * string.
     *
     * @param list non-null; the strings to combine
     * @return non-null; the combined form
     */
    public static String combineStrings(CharSequence[] list, char separator) {
        int listLength = list.length;

        if (listLength == 0) {
            return "";
        } else if (listLength == 1) {
            return (String) list[0];
        }

        int strLength = 0;

        for (Object o : list) {
            strLength += ((String) o).length();
        }

        StringBuilder sb = new StringBuilder(strLength);
        for (Object temp : list) {
            if (temp == null || TextUtils.isEmpty(temp.toString())) {
                continue;
            }
            sb.append(temp).append(separator);
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }


    public static List<PrayerAlarmDetail> getPrayerAlarmList() {
        ArrayList<PrayerAlarmDetail> list = new ArrayList<>();
        List<PrayerTimeInfo> prayerTimeInfos = getPrayerTimeList();
        if (prayerTimeInfos != null && !prayerTimeInfos.isEmpty()) {
            for (PrayerTimeInfo temp : prayerTimeInfos) {
                PrayerAlarmDetail prayerAlarmDetail = PrayerAlarmDetail.convertFromValues(temp);
                if (prayerAlarmDetail != null) {
                    long tempTime = getNextAlarmTimeMillis(prayerAlarmDetail);
                    if (tempTime > 0) {
                        prayerAlarmDetail.alarmTimeInMillis = tempTime;
                    }
                    list.add(prayerAlarmDetail);
                }
            }
        }
        Logger.i("获取祈祷时间：" + list);
        return list;
    }

    private static List<PrayerTimeInfo> getPrayerTimeList() {
        List<PrayerTimeInfo> prayerTimeList = null;
        PrayerTimesCoordinator prayerTimesCoordinator = new PrayerTimesCoordinator();
        //获取本地经纬度
        String lat = Settings.Global.getString(BaseApp.getInstance().getContentResolver(),"LAT");
        String longitude =  Settings.Global.getString(BaseApp.getInstance().getContentResolver(),"LONG");

        if ((lat !=null && !lat.equals("-999")) && (longitude !=null && !longitude.equals("-999"))) {
            prayerTimesCoordinator.updateParameters(android.text.format.DateFormat.is24HourFormat(BaseApp.getInstance()));
            TimeZone timeZone = TimeZone.getDefault();
            int time = timeZone.getRawOffset(); //获取时差，返回值毫秒
            prayerTimeList = prayerTimesCoordinator.getPrayerTimeData(
                    Double.parseDouble(lat),
                    Double.parseDouble(longitude),
                    (double) time / 1000 / 60 / 60
            );
            prayerTimeList.remove(prayerTimeList.size() - 1);
        }

        return prayerTimeList;
    }

    /**
     * 获取下次运动挑战提醒的时间
     */
    public static PrayerAlarmDetail getNextPrayerAlarmDetail(List<PrayerAlarmDetail> prayerAlarmDetailList) {
        if (prayerAlarmDetailList == null || prayerAlarmDetailList.isEmpty()) {
            Logger.w("祈祷时间列表为空");
            return null;
        }
        List<PrayerAlarmDetail> temp = new ArrayList<>();
        for (PrayerAlarmDetail detail : prayerAlarmDetailList) {
            if (detail.alarmTimeInMillis > System.currentTimeMillis()) {
                temp.add(detail);
            }
        }

        PrayerAlarmDetail nextAlarm = null;
        for (PrayerAlarmDetail detail : temp) {
            if (nextAlarm == null
                    || nextAlarm.alarmTimeInMillis > detail.alarmTimeInMillis) {
                nextAlarm = detail;
            }
        }
        return nextAlarm;
    }

    /**
     * 获取闹钟具体的响铃时间
     *
     * @param detail 闹钟对象
     */
    public static long getNextAlarmTimeMillis(PrayerAlarmDetail detail) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, detail.getHour());
        cal.set(Calendar.MINUTE, detail.getMinute());
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        final long timeInMillis = cal.getTimeInMillis();
        if (timeInMillis > System.currentTimeMillis()) {
            return timeInMillis;
        }
        cal.add(Calendar.DAY_OF_MONTH, 1);
        return cal.getTimeInMillis();
    }


    /**
     * 获取12小时制格式
     *
     * @param time   10:00、23:22格式
     * @param locale
     * @return 返回 10:00 AM、11:22 PM格式
     */
    public static String to12HourFormat_AM_PM(String time, Locale locale) {
        try {
            SimpleDateFormat hourFormat = new SimpleDateFormat("hh:mm", locale);
            return DateFormat
                    .getTimeInstance(DateFormat.SHORT, locale)
                    .format(hourFormat.parse(time));
        } catch (ParseException e) {
            Log.e("DATEUTILS", "to12HourFormat_AM_PM", e);
        }
        return time;
    }

    /**
     * 获取12小时制格式
     *
     * @param time   10:00、23:22格式
     * @param locale
     * @return 返回 10:00、11:22格式
     */
    public static String to12HourFormat(String time, Locale locale) {
        try {
            SimpleDateFormat hourFormat = new SimpleDateFormat("hh:mm", locale);
            return hourFormat.format(hourFormat.parse(time));
        } catch (ParseException e) {
            Log.e("DATEUTILS", "to12HourFormat: ", e);
        }
        return time;
    }


    public static String to24HourFormat(String time, Locale locale) {
        try {
            SimpleDateFormat hourFormat = new SimpleDateFormat("HH:mm", locale);
            return hourFormat.format(hourFormat.parse(time));
        } catch (ParseException e) {
            Log.e("DATEUTILS", "to24HourFormat: ", e);
        }
        return time;
    }


    public static byte[] toByteArray(Parcelable parcelable){
        Parcel parcel = Parcel.obtain();
        parcelable.writeToParcel(parcel,0);
        byte[] result = parcel.marshall();
        parcel.recycle();
        return result;
    }


    public  static <T> T toParcelable(byte[] bytes, Parcelable.Creator<T> creator){
        Parcel parcel = Parcel.obtain();
        parcel.unmarshall(bytes,0,bytes.length);
        parcel.setDataPosition(0);
        T result = creator.createFromParcel(parcel);
        parcel.recycle();
        return result;
    }
}
